<script setup>
import { ref, reactive, onMounted } from 'vue'
import request from '../utils/request'
import { useRouter } from 'vue-router'

import {defineUser} from "../store/userStore.js"
let sysUser=defineUser()

let router=useRouter()

let loginUser=reactive({
  username:"",
  userPwd:""
})

let usernameMsg=ref("")
let userPwdMsg=ref("")

// 动态符号数据
const symbols = ref([
  { icon: '🚀', text: '智能监控', delay: '0s' },
  { icon: '🎯', text: '精准识别', delay: '0.5s' },
  { icon: '🔍', text: '实时分析', delay: '1s' },
  { icon: '⚡', text: '快速响应', delay: '1.5s' },
  { icon: '🛡️', text: '安全防护', delay: '2s' },
  { icon: '📊', text: '数据统计', delay: '2.5s' }
])

// 视频背景相关
const backgroundVideo = ref(null)
const videoLoaded = ref(false)
const videoError = ref(false)

function checkUsername(){
  //定义正则表达式
  var reg=/^[\u4e00-\u9fa5a-zA-Z0-9_]{2,16}$/;
  //获得用户输入的信息
  var username=loginUser.username
  //格式有误时
  if(!reg.test(username)){
    usernameMsg.value="用户名格式有误"
    return false
  }
  usernameMsg.value="用户名格式正确"
  return true;
}

function checkUserPwd(){
  var reg=/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,20}$/
  var userPwd=loginUser.userPwd

  if(!reg.test(userPwd)){
    userPwdMsg.value="密码格式有误（8-20位，必须包含大小写字母、数字、特殊字符）"
    return false
  }
  userPwdMsg.value="密码格式正确"
  return true
}

function checkForm(){//表单提交时校验用户名和密码格式
  var f1=checkUserPwd()
  var f2=checkUsername()

  return f1&&f2
}

//登陆功能
async function login(){
  //表单数据格式都正确再提交
  if(!checkForm()){
    return
  }

  try {
    let {data}=await request.post("/user/login",loginUser)
    if(data.code==501){
      router.push("/loginUsernameError")
    }else if(data.code==503){
      router.push("/loginUserPwdError")
    }else if(data.code==200){
      //获得登陆用户的用户信息，更新到pinia中
      sysUser.uid=data.data.loginUser.uid
      sysUser.username=data.data.loginUser.username
      //跳转到showSchedule
      router.push("/showSchedule")
    }else{
      alert("未知错误")
    }
  } catch (error) {
    console.error('登录失败:', error);
    alert("网络错误，请检查后端服务是否启动")
  }
}

// 初始化particlesJS
function initParticles() {
  if (typeof particlesJS !== 'undefined') {
    particlesJS("particles-bg", {
      "particles": {
        "number": { "value": 40, "density": { "enable": true, "value_area": 800 } },
        "color": { "value": "#ffffff" },
        "shape": { "type": "circle" },
        "opacity": { "value": 0.7, "random": true },
        "size": { "value": 8, "random": true },
        "move": {
          "enable": true,
          "speed": 1.5,
          "direction": "top",
          "straight": false,
          "out_mode": "out"
        }
      },
      "interactivity": {
        "events": {
          "onhover": { "enable": true, "mode": "bubble" },
          "onclick": { "enable": true, "mode": "repulse" }
        },
        "modes": {
          "bubble": { "distance": 120, "size": 12, "duration": 2, "opacity": 0.6 },
          "repulse": { "distance": 100, "duration": 0.4 }
        }
      },
      "retina_detect": true
    });
  }
}

// 视频背景处理
const initVideoBackground = () => {
  if (backgroundVideo.value) {
    const video = backgroundVideo.value
    
    console.log('开始初始化视频背景')
    console.log('视频源:', video.src || video.currentSrc)
    
    // 视频加载成功
    video.addEventListener('loadeddata', () => {
      videoLoaded.value = true
      videoError.value = false
      console.log('视频背景加载成功，视频时长:', video.duration)
    })
    
    // 视频加载失败
    video.addEventListener('error', (e) => {
      videoError.value = true
      videoLoaded.value = false
      console.log('视频背景加载失败:', e)
      console.log('错误详情:', video.error)
    })
    
    // 视频开始播放
    video.addEventListener('play', () => {
      console.log('视频开始播放')
    })
    
    // 视频暂停
    video.addEventListener('pause', () => {
      console.log('视频暂停')
    })
    
    // 尝试播放视频
    video.play().catch(error => {
      console.log('视频自动播放失败:', error)
      videoError.value = true
    })
  } else {
    console.log('视频元素未找到')
  }
}

// 组件挂载时初始化
onMounted(() => {
  // 延迟初始化，确保DOM已渲染
  setTimeout(() => {
    initParticles();
    initVideoBackground();
  }, 100);
});

</script>

<template>
    <div id="particles-bg"></div>
    <!-- 视频背景 -->
    <div class="video-background">
        <video 
            ref="backgroundVideo"
            autoplay 
            muted 
            loop 
            playsinline
            class="background-video">
            <source src="/用 C 语言建立链表.mp4" type="video/mp4">
            <!-- 如果视频加载失败，显示静态背景 -->
            <div class="fallback-background"></div>
        </video>
        <div class="video-overlay"></div>
    </div>
    <div class="login-bg">
        <div class="login-container">
            <!-- 登录表单 -->
            <div class="login-card">
                <h2 class="login-title">欢迎回来</h2>
                <div class="login-subtitle">请登录您的账号</div>
                <form @submit.prevent="login()">
                    <div class="form-group">
                        <label for="usernameInput">用户名</label>
                        <div class="input-wrapper">
                            <span class="input-icon">👤</span>
                            <input class="ipt" type="text" id="usernameInput" v-model="loginUser.username" placeholder="请输入用户名" @blur="checkUsername()">
                        </div>
                        <span id="usernameMsg" class="msg" v-text="usernameMsg"></span>
                    </div>
                    <div class="form-group">
                        <label for="userPwdInput">密码</label>
                        <div class="input-wrapper">
                            <span class="input-icon">🔒</span>
                            <input class="ipt" type="password" id="userPwdInput" v-model="loginUser.userPwd" placeholder="请输入密码（8-20位，包含大小写字母、数字、特殊字符）" @blur="checkUserPwd()">
                        </div>
                        <span id="userPwdMsg" class="msg" v-text="userPwdMsg"></span>
                    </div>
                    <div class="form-row">
                        <label class="remember-me"><input type="checkbox" name="remember"> 记住我</label>
                        <router-link to="/forgot-password" class="forgot-link">忘记密码？</router-link>
                    </div>
                    <div class="buttonContainer">
                        <input class="btn1" type="submit" value="登 录">
                    </div>
                </form>
                <div class="register-tip">还没有账号？<router-link to="/regist" class="register-link">立即注册</router-link></div>
            </div>
        </div>
    </div>
</template>
        

<style scoped>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body, html {
    height: 100%;
    font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
}

#particles-bg {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #d6e0ff 0%, #e0c3fc 100%);
    z-index: -2;
    overflow: hidden;
}

.video-background {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: -1;
    overflow: hidden;
}

.background-video {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    opacity: 1;
    transition: opacity 0.5s ease;
}

.video-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, rgba(0, 0, 0, 0.1) 0%, rgba(0, 0, 0, 0.2) 100%);
    backdrop-filter: blur(0px);
}

.fallback-background {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #d6e0ff 0%, #e0c3fc 100%);
}

/* particles.js 会自动处理粒子样式 */
.login-bg {
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
}

.login-container {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    max-width: 500px;
    width: 100%;
    margin-left: 10%;
}


.login-card {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 18px;
    box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.2);
    padding: 36px 30px 24px 30px;
    min-width: 340px;
    max-width: 400px;
    display: flex;
    flex-direction: column;
    align-items: stretch;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.3);
}
.login-title {
    text-align: center;
    color: #2d2d4b;
    font-size: 26px;
    font-weight: 700;
    margin-bottom: 6px;
}
.login-subtitle {
    text-align: center;
    color: #888;
    font-size: 15px;
    margin-bottom: 22px;
}
.form-group {
    display: flex;
    flex-direction: column;
    margin-bottom: 18px;
}
.form-group label {
    margin-bottom: 6px;
    color: #3a7ca5;
    font-size: 15px;
    font-weight: 500;
}
.input-wrapper {
    display: flex;
    align-items: center;
    background: #f7f7fb;
    border-radius: 6px;
    border: 1.5px solid #e0e0ef;
    padding: 0 10px;
    transition: border-color 0.2s;
}
.input-wrapper:focus-within {
    border-color: #b39ddb;
}
.input-icon {
    font-size: 18px;
    color: #b39ddb;
    margin-right: 6px;
}
.ipt {
    border: none;
    background: transparent;
    padding: 10px 0;
    font-size: 16px;
    outline: none;
    flex: 1;
}
.msg {
    min-height: 18px;
    font-size: 13px;
    margin-top: 3px;
    color: #e74c3c;
    transition: color 0.2s;
}
.form-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 18px;
}
.remember-me {
    font-size: 14px;
    color: #888;
    user-select: none;
}
.forgot-link {
    font-size: 14px;
    color: #b39ddb;
    text-decoration: none;
    transition: color 0.2s;
}
.forgot-link:hover {
    color: #7e57c2;
}
.buttonContainer {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 6px;
    margin-bottom: 10px;
}
.btn1 {
    border: none;
    border-radius: 6px;
    padding: 10px 0;
    width: 100%;
    background: linear-gradient(90deg, #b39ddb 0%, #a18cd1 100%);
    color: #fff;
    font-size: 17px;
    font-weight: 600;
    cursor: pointer;
    box-shadow: 0 2px 8px rgba(163, 148, 255, 0.08);
    transition: background 0.2s, transform 0.1s;
    letter-spacing: 2px;
}
.btn1:hover, .btn1:focus {
    background: linear-gradient(90deg, #a18cd1 0%, #b39ddb 100%);
    transform: translateY(-2px) scale(1.03);
}
.register-tip {
    text-align: center;
    color: #888;
    font-size: 14px;
    margin-top: 8px;
}
.register-link {
    color: #b39ddb;
    text-decoration: none;
    margin-left: 2px;
    transition: color 0.2s;
}
.register-link:hover {
    color: #7e57c2;
}

@media (max-width: 768px) {
    .login-container {
        max-width: 90%;
        margin-left: 5%;
        justify-content: flex-start;
    }
}

@media (max-width: 480px) {
    .login-container {
        margin-left: 2%;
        justify-content: center;
    }
    
    .login-card {
        padding: 18px 6vw 18px 6vw;
        min-width: unset;
    }
    .btn1 {
        font-size: 15px;
    }
}
#particles-bg {
    position: fixed;
    left: 0; top: 0; right: 0; bottom: 0;
    width: 100vw;
    height: 100vh;
    z-index: 0;
    pointer-events: auto;
}
.login-bg, .login-card {
    position: relative;
    z-index: 1;
}
</style>

